# -*- coding:utf-8 -*-
'''
完成图片验证码和短信验证码的功能
'''
import logging
import random

from flask import current_app
from flask import jsonify
from flask import make_response
from flask import request

from ihome import redis_store
from ihome.api_1_0 import api
from ihome.libs.yuntongxin.sms import CCP
from ihome.models import User
from ihome.utils.captcha.captcha import captcha
from ihome.utils.response_code import RET


# 获取图形验证码
# 请求方式: GET
# 路由: image_codes
@api.route('/image_codes/<image_code_id>')
def get_image_code(image_code_id):
    print '*' * 10, '获取图片验证码', '*' * 10
    # 1. 使用工具类生成图形验证码
    name, text, image_data = captcha.generate_captcha()

    # 2. 将验证码的数据和编号存储到redis中
    try:
        redis_store.setex('image_code_%s' % image_code_id, 300, text)
    except Exception as e:
        logging.error(e)
        resp = {
            'error': RET.DBERR,
            'errmsg': 'redis保存出错'
        }
        return jsonify(resp)

    # 3. 返回图像
    resp = make_response(image_data)
    resp.headers['Content-Type'] = 'image/jpg'
    return resp


# 获取短信验证码
# 请求方式: GET
# 路由: sms_codes
# 参数: 手机号 / 图片验证码 / 编号
# URL /api/v1_0/sms_codes/17612345678?image_code=abcd&image_code_id=UUID
# http://127.0.0.1:5000/api/v1_0/sms_codes/11111111111?code=xq5m&codeId=b7303c7f-e3aa-406f-8aa6-b59f6a2a18a3
@api.route('/sms_codes/<re(r"1[3456789][0-9]{9}"):mobile_num>')
def get_sms_codes(mobile_num):
    print '*' * 10, '获取短信验证码', '*' * 10
    # 一 获取参数:图片验证码 编号
    print '请求链接:', request.url
    image_code = request.args.get("image_code")
    image_code_id = request.args.get("image_code_id")

    # 二 校验参数: 完整性
    if not all([image_code, image_code_id]):
        resp = {
            'errno': RET.PARAMERR,
            'errmsg': '参数不全'
        }
        return jsonify(resp)

    # 三 逻辑处理
    #   1. 从redis中获取数据对比
    #   2.判断用户是否注册过
    #   3.调用第三方SDK发送短信

    # 1 从redis中获取数据对比
    # 1.1 获取redis数据
    try:
        real_image_code = redis_store.get('image_code_%s' % image_code_id)
    except Exception as e:
        logging.error(e)
        resp = {
            'errno': RET.DBERR,
            'errmsg': 'redis读取失败'
        }
        return jsonify(resp)

    # 1.2 判断数据是否为None
    # 数据库获取操作,一定要判断None.只要查询不出数据,就是返回None
    if real_image_code is None:
        resp = {
            'errno': RET.NODATA,
            'errmsg': '未查询到有关数据'
        }
        return jsonify(resp)

    # 1.3 无论对比是否成功,先删除服务器的验证码,每个图像验证码只能验证一次
    try:
        redis_store.delete('image_code_%s' % image_code_id)
    except Exception as e:
        logging(e)
        resp = {
            'errno': RET.DBERR,
            'errmsg': 'redis删除操作失败'
        }
        return jsonify(resp)

    # 1.4 对比验证码数据
    # ABCD(服务器) = abcd (用户输入)
    if real_image_code.lower() != image_code.lower():
        resp = {
            'errno': RET.DATAERR,
            'errmsg': '验证码填写错误,请刷新后重试'
        }
        return jsonify(resp)

    # 2 判断用户是否注册过
    # 2.1 查询数据库的操作
    # 2.2 判断数据是否为None
    try:
        user = User.query.filter_by(mobile=mobile_num).first()
    except Exception as e:
        logging.error(e)
        resp = {
            'errno': RET.DBERR,
            'errmsg': 'redis查询失败'
        }
        return jsonify(resp)
    else:
        # 执行成功 走else
        if user is not None:
            resp = {
                'errno': RET.DATAEXIST,
                'errmsg': '该手机号已经被注册,请更换手机好'
            }
            return jsonify(resp)

    # 3 调用第三方SDK发送短信
    # 3.1 创建6为短信验证码
    sms_code = '%06d' % random.randint(0, 999999)
    # 3.2 保存到redis中
    try:
        redis_store.set('sms_code_%s' % mobile_num, sms_code)
    except Exception as e:
        logging(e)
        resp = {
            'errno': RET.DBERR,
            'errmsg': 'redis数据保存失败'
        }
        return jsonify(resp)

    # 3.3 发送验证码
    ccp = CCP()
    result = ccp.send_template_sms(mobile_num, [sms_code, 5], 1)

    # 四 返回数据
    if result == '000000':
        resp = {
            'errno': RET.OK,
            'errmsg': '发送短信成功'
        }
        return jsonify(resp)
    else:
        resp = {
            'errno': RET.THIRDERR,
            'errmsg': '发送短信失败'
        }
        return jsonify(resp)
